package com.baide.sanguanheyi.plc;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author: create by DFX
 * @Date: 2020/4/23 22:13
 * @Version: V1.0.0
 * @Tips: 继承自 SimpleChannelInboundHandler，这个类实现了ChannelInboundHandler 接口，ChannelInboundHandler
 * 提供了许多事件处理的接口方法，然后你可以覆盖这些方法。现在仅仅只需要继承 SimpleChannelInboundHandler
 * 类而不是你自己去实现接口方法
 */
@Component
@ChannelHandler.Sharable
public class NioServerHandler extends SimpleChannelInboundHandler<String> {

    public static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    private Logger logger = LoggerFactory.getLogger(NioServerHandler.class);
    private int obr_line_num = 0;

    @Autowired
    NioObjectHandle handle;
    @Autowired
    NioServer nioServer;
    @Autowired
    PlcConfig plcConfig;

    /**
     * 覆盖了 handlerAdded() 事件处理方法 每当从服务端收到新的客户端连接时客户端的 Channel 存入 ChannelGroup列表中
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        String ipAddress = channel.remoteAddress().toString().substring(1, channel.remoteAddress().toString().indexOf(":"));
        if (ipAddress.equals(plcConfig.getPlc())) {  // PLC
            nioServer.callBack.PLCConnectSuccess();
        } else {  // OBR
            if (checkOBRStatus(ipAddress, 1) == 1) { // 部分连接
                nioServer.callBack.OBRConnectSuccess("已连接");
            } else { // 全部连接
                nioServer.callBack.OBRConnectSuccess("连接中");
            }
        }
        NioChannelMap.add(channel.remoteAddress().toString().substring(1, channel.remoteAddress().toString().indexOf(":")), channel);
        channels.add(channel);
    }

    /**
     * 覆盖了 channelRead0() 事件处理方法。每当从服务端读到客户端写入信息时相应
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String in) throws Exception {
        logger.info("收到PLC信息：" + in);
        Channel channel = ctx.channel();
        try {
            handle.receiver(channel, in);
        } catch (Exception e) {
            e.printStackTrace();
            channel.writeAndFlush("gg");
        }
    }

    /**
     * 覆盖了 channelActive() 事件处理方法。服务端监听客户端活动
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        logger.info("NioServerHandler:" + channel.remoteAddress().toString().substring(1, channel.remoteAddress().toString().indexOf(":")) + "在线#" + channel.remoteAddress());
    }

    private int checkOBRStatus(String ipAddress, int conn) {
        int result = -1;
        if (conn == 1) { // 上线
            if (!ipAddress.equals(plcConfig.getPlc())) {  // OBR1
                obr_line_num = obr_line_num + 1;
            }
        } else { // 下线
            if (!ipAddress.equals(plcConfig.getPlc())) {  // OBR1
                obr_line_num = obr_line_num - 1;
            }
        }

        if (obr_line_num == plcConfig.getObr_num()) {
            result = 1;
        } else if (obr_line_num > 0 && obr_line_num < plcConfig.getObr_num()) {
            result = 0;
        }

        return result;
    }

    /**
     * 覆盖了channelInactive() 事件处理方法。服务端监听到客户端不活动 客户端不活动后先执行，然后执行handlerRemoved
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        String clientId = NioChannelMap.remove(channel);
        logger.info("NioServerHandler:" + channel.remoteAddress() + "下线#" + clientId);
    }

    /**
     * 覆盖了handlerRemoved() 事件处理方法。每当从服务端收到客户端断开时，客户端的 Channel 移除列表中 ChannelGroup
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        logger.info("NioServerHandler:客户端离开:" + channel.remoteAddress());
        String ipAddress = channel.remoteAddress().toString().substring(1, channel.remoteAddress().toString().indexOf(":"));
        if (ipAddress.equals(plcConfig.getPlc())) {  // PLC
            nioServer.callBack.PLCConnectOff();
        } else {  // OBR
            if (checkOBRStatus(ipAddress, 2) == 0) { // 部分连接
                nioServer.callBack.OBRConnectOff("连接中");
            } else { // 未连接
                nioServer.callBack.OBRConnectOff("未连接");
            }
        }
        NioChannelMap.remove(channel);
        channels.remove(ctx.channel());
    }

    /**
     * 一段时间未进行读写操作 回调
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        super.userEventTriggered(ctx, evt);
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;

            if (event.state().equals(IdleState.READER_IDLE)) {
                // 未进行读操作
                // 超时关闭channel
                ctx.close();
            } else if (event.state().equals(IdleState.WRITER_IDLE)) {
                // 未进行读操作

            } else if (event.state().equals(IdleState.ALL_IDLE)) {
                // 未进行读写
                //	logger.info("ALL_IDLE");
                // 发送心跳消息
            }

        }
    }

    /***
     * exceptionCaught() 事件处理方法是当出现 Throwable 对象才会被调用，即当 Netty 由于 IO
     * 错误或者处理器在处理事件时抛出的异常时。在大部分情况下，捕获的异常应该被记录下来并且把关联的 channel
     * 给关闭掉,然而这个方法的处理方式会在遇到不同异常的情况下有不同的实现，比如你可能想在关闭连接之前发送一个错误码的响应消息
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { // (7)
        try {
            Channel channel = ctx.channel();
            String clientId = NioChannelMap.remove(channel);
            logger.info("NioServerHandler:" + channel.remoteAddress() + "异常#" + clientId);
            ctx.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
